package com.hyyt.shopjsp.mallSummary.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.order.service.IShopOrdersService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.common.*;
import com.hyyt.shopjsp.util.export.ExportExcel;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/03/20 0024下午 3:28.
 */

@Controller
@RequestMapping("/back/mallSummary")
public class MallSummaryController extends BaseController{
	
	private Logger log = Logger.getLogger(MallSummaryController.class);
	private String basePath = "/back/shop/mallSummary/";
	@Resource
	private IShopOrdersService shopOrdersService;
	/**
	 * 进入订单统计表页面管理
	 *
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoCollectiveOrderPage")
	public String gotoCollectiveOrderPage(){
		return basePath+"collectiveOrderList";
	}

	/**
	 * 查询订单统计表页面
	 * @param page
	 * @param shopName
	 * @param ordersState
	 * @param shopInfoType
	 * @param beginTime
	 * @param endTime
	 * @param response
	 */
	@RequestMapping(value="ListCollectiveOrder",method=RequestMethod.POST)
	@ResponseBody
	public void ListCollectiveOrder(Page page,String shopName,String ordersState,String shopInfoType,String beginTime,String endTime, HttpServletResponse response){
		Map<String, Object> param = new HashMap<>();
		if(Utils.objectIsNotEmpty(shopName)){ //店铺名
			param.put("shopName",shopName);
		}
		if(Utils.objectIsNotEmpty(ordersState)){
			if("1".equals(ordersState)){ //生成订单(未付款)
				param.put("ordersState",1);
			}else if("2".equals(ordersState)){ //生成订单(已付款)
				param.put("ordersState",2);
			}else if("5".equals(ordersState)){ //已完成
				param.put("ordersState",5);
			}else if("9".equals(ordersState)){ //已付款(不含已取消)
				param.put("ordersState",9);
			}else{ //配货 发货 取消订单
				param.put("ordersState",ordersState);
			}
		}
		//店铺类型
		if(Utils.objectIsNotEmpty(shopInfoType)){
			param.put("shopInfoType",shopInfoType);
		}
		//判断交易开始时间和交易结束时间都为空时，查询当月的
		if(Utils.objectIsEmpty(beginTime) && Utils.objectIsEmpty(endTime)){
			//获取前月的第一天
			Calendar cal=Calendar.getInstance();//获取当前日期
			int year=cal.get(Calendar.YEAR); //年份  例如2017
			int month=cal.get(Calendar.MONTH)+1; //当前月份 例如11
			param.put("sameMonth",year+"-"+month); //当前年份+月份 例如2017-11
		}
		if(Utils.objectIsNotEmpty(beginTime)){ //交易开始时间不为空时查询交易开始时间
			param.put("beginTime",beginTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){ //交易结束时间不为空时查询交易结束时间
			param.put("endTime",endTime);
		}
		//查询订单统计数量
		int totalRecordCount=shopOrdersService.ordersCollectiveCount(param);
		//分页
		page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		//查询订单统计集合数据
		List <Map<String,Object>> collectiveOrderList=shopOrdersService.ordersCollectiveList(param,page.getPageRecordBeginIndex(), page.getPageSize());
		//获取税率
		if(collectiveOrderList!=null&&collectiveOrderList.size()>0){
			for(Map<String,Object> m:collectiveOrderList){//格式化创建时间
				if(m.get("invoiceType")==null||Integer.parseInt(String.valueOf(m.get("invoiceType")))==1){
					m.put("taxRate", 0);
					m.put("taxRateAmount", 0);
				}else if(Integer.parseInt(String.valueOf(m.get("invoiceType")))==2){
					String generalRates=String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.INVOICE_TYPE_RATES_GENERAL));
					if (Utils.objectIsEmpty(generalRates) || "null".equals(generalRates)) generalRates = "0";
					BigDecimal b=new BigDecimal(generalRates);
					m.put("taxRate", b);
					m.put("taxRateAmount", b.multiply((BigDecimal)m.get("totalAmount")).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP));
				}else if(Integer.parseInt(String.valueOf(m.get("invoiceType")))==3){
					String vatRates=String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.INVOICE_TYPE_RATES_VAT));
					if (Utils.objectIsEmpty(vatRates) || "null".equals(vatRates)) vatRates = "0";
					BigDecimal b=new BigDecimal(vatRates);
					m.put("taxRate", b);
					m.put("taxRateAmount", b.multiply((BigDecimal)m.get("totalAmount")).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP));
				}
			}
		}
		 param.clear();
		 param.put("total", totalRecordCount);// total键 存放总记录数，必须的
		 param.put("rows", collectiveOrderList);// rows键 存放每页记录 list
		 ResultMsg.create(param, response);  //把内容发送到页面
	}


	/**
	 * 导出订单统计excel
	 * @param shopName
	 * @param ordersState
	 * @param shopInfoType
	 * @param beginTime
	 * @param endTime
	 * @param response
	 */
	@RequestMapping("exportCollectiveOrder")
	public void exportCollectiveOrder(String shopName,String ordersState,String shopInfoType,String beginTime,String endTime, HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> param = new HashMap<>();
		if(Utils.objectIsNotEmpty(shopName)){ //店铺名
			param.put("shopName",shopName);
		}
		if(Utils.objectIsNotEmpty(ordersState)){
			if("1".equals(ordersState)){ //生成订单(未付款)
				param.put("ordersState",1);
			}else if("2".equals(ordersState)){ //生成订单(已付款)
				param.put("ordersState",2);
			}else if("5".equals(ordersState)){ //已完成
				param.put("ordersState",5);
			}else if("9".equals(ordersState)){ //已付款(不含已取消)
				param.put("ordersState",9);
			}else{ //配货 发货 取消订单
				param.put("ordersState",ordersState);
			}
		}
		//店铺类型
		if(Utils.objectIsNotEmpty(shopInfoType)){
			param.put("shopInfoType",shopInfoType);
		}
		//判断交易开始时间和交易结束时间都为空时，查询当月的
		if(Utils.objectIsEmpty(beginTime) && Utils.objectIsEmpty(endTime)){
			//获取前月的第一天
			Calendar cal=Calendar.getInstance();//获取当前日期
			int year=cal.get(Calendar.YEAR); //年份  例如2017
			int month=cal.get(Calendar.MONTH)+1; //当前月份 例如11
			param.put("sameMonth",year+"-"+month); //当前年份+月份 例如2017-11
		}
		if(Utils.objectIsNotEmpty(beginTime)){ //交易开始时间不为空时查询交易开始时间
			param.put("beginTime",beginTime);
		}
		if(Utils.objectIsNotEmpty(endTime)){ //交易结束时间不为空时查询交易结束时间
			param.put("endTime",endTime);
		}
		//查询订单统计集合数据
		List <Map<String,Object>> collectiveOrderList=shopOrdersService.ordersCollectiveList(param);
		//获取税率
		if(collectiveOrderList!=null&&collectiveOrderList.size()>0){
			for(Map<String,Object> m:collectiveOrderList){//格式化创建时间
				if(m.get("invoiceType")==null||Integer.parseInt(String.valueOf(m.get("invoiceType")))==1){
					m.put("taxRate", 0);
					m.put("taxRateAmount", 0);
				}else if(Integer.parseInt(String.valueOf(m.get("invoiceType")))==2){
					String generalRates=String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.INVOICE_TYPE_RATES_GENERAL));
					if (Utils.objectIsEmpty(generalRates) || "null".equals(generalRates)) generalRates = "0";
					BigDecimal b=new BigDecimal(generalRates);
					m.put("taxRate", b);
					m.put("taxRateAmount", b.multiply((BigDecimal)m.get("totalAmount")).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP));
				}else if(Integer.parseInt(String.valueOf(m.get("invoiceType")))==3){
					String vatRates=String.valueOf(RedisDataReadUtil.getSysConfig(StringStaticKey.INVOICE_TYPE_RATES_VAT));
					if (Utils.objectIsEmpty(vatRates) || "null".equals(vatRates)) vatRates = "0";
					BigDecimal b=new BigDecimal(vatRates);
					m.put("taxRate", b);
					m.put("taxRateAmount", b.multiply((BigDecimal)m.get("totalAmount")).divide(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP));
				}
			}
		}
		SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
		List<Map<String,Object>> mallSummary = new ArrayList<>();
		if(collectiveOrderList!=null&&collectiveOrderList.size()>0){
			for (Map<String,Object> collectiveOrder : collectiveOrderList) {
				Map<String,Object> map = new HashMap<>();
				map.put("ordersNo",collectiveOrder.get("ordersNo"));
				map.put("shopName",collectiveOrder.get("shopName"));
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("shopInfoType")))){
					if(Integer.parseInt(String.valueOf(collectiveOrder.get("shopInfoType")))==1){
						map.put("shopInfoType","自营店铺");
					}else{
						map.put("shopInfoType","入驻店铺");
					}
				}else{
					map.put("shopInfoType","");
				}
				map.put("loginName",collectiveOrder.get("loginName"));
				map.put("consignee",collectiveOrder.get("consignee"));
				map.put("totalAmount",collectiveOrder.get("totalAmount"));
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("discount")))){
					map.put("discount",collectiveOrder.get("discount"));
				}else{
					map.put("discount","无折扣");
				}
				map.put("userCoin",collectiveOrder.get("userCoin"));
				map.put("changeAmount",collectiveOrder.get("changeAmount"));
				if(Utils.objectIsNotEmpty(collectiveOrder.get("orderCouponAmount"))){
					map.put("orderCouponAmount",collectiveOrder.get("orderCouponAmount"));
				}else{
					map.put("orderCouponAmount","0.00");
				}
				map.put("freight",collectiveOrder.get("freight"));
				map.put("taxRate",collectiveOrder.get("taxRate"));
				map.put("taxRateAmount",collectiveOrder.get("taxRateAmount"));
				map.put("finalAmount",collectiveOrder.get("finalAmount"));
				map.put("virtualCoinNumber",collectiveOrder.get("virtualCoinNumber"));
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("createTime")))){
					map.put("createTime",collectiveOrder.get("createTime"));
				}else{
					map.put("createTime", "");
				}
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("payTime")))){
					map.put("payTime",collectiveOrder.get("payTime"));
				}else{
					map.put("payTime","");
				}
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("distributionTime")))){
					map.put("distributionTime",collectiveOrder.get("distributionTime"));
				}else{
					map.put("distributionTime","");
				}
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("deliversTime")))){
					map.put("deliversTime",collectiveOrder.get("deliversTime"));
				}else{
					map.put("deliversTime","");
				}
				if(Utils.objectIsNotEmpty(String.valueOf(collectiveOrder.get("receivesTime")))){
					map.put("receivesTime",collectiveOrder.get("receivesTime"));
				}else{
					map.put("receivesTime","");
				}
				mallSummary.add(map);
			}
		}

		String fileName ="订单统计信息";
		String columnNames[] = {"订单编号","商户店铺名称","店铺类型","买家会员名称","收货人名称","商品总金额(元)","折扣","使用积分","积分抵扣金额(元)","优惠券抵扣(元)","运费(元)","税率(%)","税金(元)","订单应付金额(元)","赠送积分","订单生成时间","付款时间","配货时间","发货时间","收货时间"};
		String keys[] = {"ordersNo","shopName","shopInfoType","loginName","consignee","totalAmount","discount","userCoin","changeAmount","orderCouponAmount","freight","taxRate","taxRateAmount","finalAmount","virtualCoinNumber","createTime","payTime","distributionTime","deliversTime","receivesTime"};
		try {
			ExportExcel.download(fileName,mallSummary,columnNames,keys,request,response);
		} catch (IOException e) {
			logger.error("导出Excel失败！");
		}

	}
}
